package com.example.smartvillage.cunmin;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.os.HandlerCompat;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.example.smartvillage.R;
import com.example.smartvillage.model.Commodity;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;

public class DealActivity extends AppCompatActivity {
    private static final String TAG = "二手交易中心";
    private MyAdapter myAdapter;
    SwipeRefreshLayout swipeRefreshLayout;
    ListView LSVSD;
    FloatingActionButton floatingActionButton;
    Handler mainThreadHandler = HandlerCompat.createAsync(Looper.getMainLooper());
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deal);
        Bmob.initialize(this, "6fe8eb567bb46bfa61a97578a8e41206");
        swipeRefreshLayout = findViewById(R.id.deal_swipe_refresh);
        LSVSD = findViewById(R.id.lv);
        LSVSD.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (view.getChildAt(0) != null) {
                    swipeRefreshLayout.setEnabled(view.getFirstVisiblePosition() == 0 && view.getChildAt(0).getTop() == 0);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        floatingActionButton = findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DealActivity.this,DealEditActivity.class),0x1);
            }
        });
        //滑动刷新
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(R.color.colorPrimary));
        swipeRefreshLayout.setOnRefreshListener(onRefreshListener);
        loadData();
    }

    //刷新监听
    SwipeRefreshLayout.OnRefreshListener onRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            loadData();
            Log.d(TAG, "加载新的二手交易数据");
            mainThreadHandler.post(() -> {
                swipeRefreshLayout.setRefreshing(false);
                Log.d(TAG, "二手交易信息刷新完成");
            });
        }
    };

//从Bmob获取商品信息，加载到List里面
    private void loadData(){
        BmobQuery<Commodity> bmobQuery = new BmobQuery<Commodity>();
        bmobQuery.order("-createdAt");
        bmobQuery.findObjects(new FindListener<Commodity>() {
            @Override
            public void done(List<Commodity> list, BmobException e) {
                int[] picList = {R.drawable.index,R.drawable.index1,R.drawable.index2,R.drawable.index3,R.drawable.index4,R.drawable.index5,R.drawable.index6,R.color.white,R.color.white};
                String[] titleList = new String[list.size()],phoneList = new String[list.size()],describeList = new String[list.size()];
                for (int i = 0; i < list.size(); i++){
                    titleList[i] = list.get(i).getTitle();
                    phoneList[i] = list.get(i).getPhone();
                    describeList[i] = list.get(i).getDescribe();
                }
                myAdapter = new MyAdapter(DealActivity.this,picList,titleList,phoneList,describeList);
                LSVSD.setAdapter(myAdapter);
                myAdapter.notifyDataSetChanged();
            }
        });
    }

}
class MyAdapter extends BaseAdapter {

    Context context;
    int[] picture;
    String[] title;
    String[] phone;
    String[] describe;

    public MyAdapter(Context context, int[] picture, String[] title, String[] phone, String[] describe) {
        this.context = context;
        this.picture = picture;
        this.title = title;
        this.phone = phone;
        this.describe = describe;
    }

    @Override
    public int getCount() {
        return title.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        class ListHold {
            ImageView ivPic;
            TextView  tvTitle,tvPhone,tvDescribe;
        }

        ListHold listHold;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_deal, parent, false);
            listHold = new ListHold();
            listHold.ivPic = convertView.findViewById(R.id.commodity_picture);
            listHold.tvTitle = convertView.findViewById(R.id.commodity_tittle);
            listHold.tvPhone = convertView.findViewById(R.id.commodity_phone);
            listHold.tvDescribe = convertView.findViewById(R.id.commodity_describe);

            convertView.setTag(listHold);

        } else {
            listHold = (ListHold) convertView.getTag();
        }

        listHold.ivPic.setImageDrawable(ContextCompat.getDrawable(context, picture[position]));
        listHold.tvTitle.setText(title[position]);
        listHold.tvPhone.setText(phone[position]);
        listHold.tvDescribe.setText(describe[position]);

        return convertView;
    }
}